package com.unism.listener;

import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.unism.objType.ObjectTypeConfig;

public class GlObjectTypeConfigListener implements ServletContextListener {

	private static String OBJECTTYPECONFIGLOCATION = "objectTypeConfigLocation";

	/**
	 * 关闭应用服务器上下文时，执行此方法
	 */
	public void contextDestroyed(ServletContextEvent event) {
		// System.out.println("应用服务器关闭时！");
	}

	/**
	 * 应用服务器上下文初始化时，执行此方法
	 */
	public void contextInitialized(ServletContextEvent event) {
		ServletContext con = event.getServletContext();
		// 初始化远程命令配置文件
		this.initAppTypeConfig(con);
	}

	/**
	 * 解析远程命令配置
	 * 
	 * @param con
	 * @return
	 */
	private boolean initAppTypeConfig(ServletContext con) {
		try {
			String configName = con.getInitParameter(OBJECTTYPECONFIGLOCATION);
			if (configName == null || configName.trim().equals("")) {
				throw new Exception("在web.xml文件中，未配置配置文件名称!");
			}
			String confs[] = configName.split(",");
			String conf = null;
			for (int i = 0; i < confs.length; i++) {
				conf = confs[i].trim();
				if (conf != null && !conf.equals("")) {
					URL configFileURL = null;
					configFileURL = GlObjectTypeConfigListener.class
							.getResource("/config/" + conf);
					if (configFileURL == null) {
						configFileURL = GlObjectTypeConfigListener.class
								.getResource("/" + conf);
					}
					ObjectTypeConfig.getInstance().init(configFileURL);
				}
			}
			return true;
		} catch (Exception e) {
			System.out.println("系统启动时，初始化配置出错 !");
			System.out.println(e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

}